using MediatR;
using MeetingManagement.Application.Common;
using MeetingManagement.Domain.Entities;
using MeetingManagement.Domain.Repositories;

namespace MeetingManagement.Application.Commands.Meetings.CancelMeeting
{
    public class CancelMeetingCommandHandler : IRequestHandler<CancelMeetingCommand, bool>
    {
        private readonly IRepository<Meeting> _meetingRepo;
        private readonly IRepository<User> _userRepo;
        private readonly ISystemMessageService _msgService;
        public CancelMeetingCommandHandler(IRepository<Meeting> meetingRepo, IRepository<User> userRepo, ISystemMessageService msgService)
        {
            _meetingRepo = meetingRepo;
            _userRepo = userRepo;
            _msgService = msgService;
        }
        public Task<bool> Handle(CancelMeetingCommand request, CancellationToken cancellationToken)
        {
            var meeting = _meetingRepo.Get(request.MeetingId);
            if (meeting == null || meeting.OrganizerId != request.UserId) return Task.FromResult(false);

            meeting.Cancel();

            _meetingRepo.UpdateAsync(meeting);

            foreach (var pid in meeting.ParticipantIds)
            {
                var user = _userRepo.Get(pid);
                if (user != null) _msgService.Send(pid, $"会议[{meeting.Title}]已被发起人取消。");
            }
            return Task.FromResult(true);
        }
    }
}
